package com.ophiux.utils.common;

import java.math.BigDecimal;

public class FeeSwithUtil {
	/**
	 * 元转为分
	 * 
	 * @param amount
	 * @return
	 */
	public static String yuanToFee(String amount) {
		// hhl 2018-11-7 为了让0.035变成0.04
		amount = round(amount);

		String currency = amount.replaceAll("\\$|\\￥|\\,", ""); // 处理包含, ￥ 或者$的金额
		int index = currency.indexOf(".");
		int length = currency.length();
		Long amLong = 0l;
		if (index == -1) {
			amLong = Long.valueOf(currency + "00");
		} else if (length - index >= 3) {
			amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
		} else if (length - index == 2) {
			amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
		} else {
			amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
		}
		return amLong.toString();
	}

	/**
	 * 分转为元
	 * 
	 * @param amount
	 * @return
	 */
	public static String feeToYuan(String amount) {
		try {
			if (!amount.toString().matches("\\-?[0-9]+"))
				;
		} catch (Exception e) {
			e.printStackTrace();
		}
		int flag = 0;
		String amString = amount.toString();
		if (amString.charAt(0) == '-') {
			flag = 1;
			amString = amString.substring(1);
		}
		StringBuffer result = new StringBuffer();
		if (amString.length() == 1) {
			result.append("0.0").append(amString);
		} else if (amString.length() == 2) {
			result.append("0.").append(amString);
		} else {
			String intString = amString.substring(0, amString.length() - 2);
			for (int i = 1; i <= intString.length(); i++) {
				if ((i - 1) % 3 == 0 && i != 1) {
					// result.append(",");
				}
				result.append(intString.substring(intString.length() - i, intString.length() - i + 1));
			}
			result.reverse().append(".").append(amString.substring(amString.length() - 2));
		}
		if (flag == 1) {
			return "-" + result.toString();
		} else {
			return result.toString();
		}
	}

	public static void main(String[] args) {

		System.out.println("元转分:" + yuanToFee("0.23522"));

		System.out.println("分转元:" + feeToYuan("31231"));
		System.out.println(round("123.23", 0));
	}

	/**
	 * Description:小数四舍五入保留2位小数 保留0.12<br>
	 * 创 建 人: hhl <br>
	 * 创建日期:2018年11月6日 下午3:00:08
	 * 
	 * @param v
	 *            需要保留的小数
	 * @return
	 */
	public static String round(String v) {
		return round(v, 2);
	}

	/**
	 * Description:小数四舍五入保留小数 <br>
	 * 创 建 人: hhl<br>
	 * 创建日期:2018年11月6日 下午3:00:08
	 * 
	 * @param v
	 *            需要保留的小数
	 * @param scale
	 *            保留小数位数
	 * @return
	 */
	public static String round(String v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(v);
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue() + "";
	}
}
